package com.yksj.healthtalk.adapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import android.content.Context;
import android.database.DataSetObserver;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.yksj.healthtalk.comm.imageload.ImageLoader;
import com.yksj.healthtalk.entity.CustomerInfoEntity;
import com.yksj.healthtalk.entity.GroupInfoEntity;
import com.yksj.healthtalk.entity.MessageEntity;
import com.yksj.healthtalk.net.socket.SmartFoxClient;
import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.ui.app.AppData;
import com.yksj.healthtalk.ui.app.HTalkApplication;
import com.yksj.healthtalk.ui.friend.FriendInformUI;
import com.yksj.healthtalk.ui.salon.SalonInformationActivity;
import com.yksj.healthtalk.ui.salon.SalonNewActivity;
import com.yksj.healthtalk.utils.BitmapUtils;

public class FriendListExpandableAdapter extends BaseExpandableListAdapter{
	private Context context;
	private final Map<String, List<String>> data;
	private final LayoutInflater inflater;
	private List<String> keys;
	private HashMap<Integer, List<Integer>> map = new HashMap<Integer, List<Integer>>();
	private final String stranger;
	private final String blacklist;
	private final String friendRecent;
	private final String groupNew;
	private final ImageLoader mImageLoader;
	private boolean ISBLACKLTMORE=false;
	private boolean ISSTRANGERMORE=false;
	private final AppData mAppData;
	private IntoInfoListener  infoListener;
	private Bitmap bDown;
	private Bitmap bUp;
	private Bitmap bg;
	private BitmapDrawable bg_draw;
	private Bitmap ic_cross;
	
	public FriendListExpandableAdapter(Context context, HashMap<String, List<String>> data){
		this.context = context;
        this.data = data;
        Set<String> set = data.keySet();
        keys =new ArrayList<String>(set);
        inflater = LayoutInflater.from(context);
        stranger = context.getResources().getString(R.string.stranger);
        blacklist = context.getResources().getString(R.string.blacklist);
        friendRecent = context.getString(R.string.recentContact);
        mImageLoader = new ImageLoader(context);
        mAppData = HTalkApplication.getAppData();
    	 bDown = BitmapUtils.getBackGroundBitmap(context.getResources(), R.drawable.friend_group_arrows_down);
    	 bUp = BitmapUtils.getBackGroundBitmap(context.getResources(), R.drawable.friend_group_arrows);
    	 groupNew = context.getResources().getString(R.string.groupNew);
    	 bg = BitmapUtils.getBackGroundBitmap(context.getResources(),R.drawable.setting_title_bg);
    	 bg_draw=new BitmapDrawable(bg);
    	 ic_cross = BitmapUtils.getBackGroundBitmap(context.getResources(),R.drawable.ic_cross);
    	 
	}
	

	@Override
	public boolean areAllItemsEnabled() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public String getChild(int groupPosition, int childPosition) {
		if(keys.size() != 0)
		    return data.get(keys.get(groupPosition)).get(childPosition);
		else
		   return null;
	}

	@Override
	public long getChildId(int groupPosition, int childPosition) {
		return childPosition;
	}

	@Override
	public View getChildView(int groupPosition, int childPosition,
			boolean isLastChild, View convertView, ViewGroup parent) {
		final viewHolder holder;
		if (convertView == null){
			holder = new viewHolder();  
			convertView = inflater.inflate(R.layout.group_item, null);
			holder.image = (ImageView) convertView.findViewById(R.id.head_image);
			holder.sex = (ImageView) convertView.findViewById(R.id.head_sex);
			holder.v = (ImageView) convertView.findViewById(R.id.v);
			holder.name_tv = (TextView) convertView.findViewById(R.id.name);
			holder.note_tv = (TextView) convertView.findViewById(R.id.note);
			holder.msg = (TextView) convertView.findViewById(R.id.item_dele);
			holder.number = (TextView) convertView.findViewById(R.id.number);
			holder.line = (LinearLayout) convertView.findViewById(R.id.item_line);
			//加载更多
			holder.more = (TextView)convertView.findViewById(R.id.more);
			//列表的布局
			holder.lay = (LinearLayout)convertView.findViewById(R.id.lay);
			convertView.setTag(holder);
			convertView.setBackgroundResource(R.drawable.listview_item_selector);
		} else {
			holder = (viewHolder) convertView.getTag();
		}
		
		holder.groupId = groupPosition;
		holder.childId = childPosition;
		List<String> list = data.get(keys.get(groupPosition));
		
		if((childPosition == getChildrenCount(groupPosition) -1))
			holder.line.setVisibility(View.GONE);
		else
			holder.line.setVisibility(View.VISIBLE);
		
		//显示加载更多
		if (groupPosition==3) {
			if (data.get(keys.get(groupPosition)).size()< mAppData.blackListSize){
				if((childPosition == list.size())){
					holder.more.setVisibility(View.VISIBLE);
					holder.lay.setVisibility(View.GONE);
					holder.more.setText(R.string.loadmore);
				}else{
					holder.more.setVisibility(View.GONE);
					holder.lay.setVisibility(View.VISIBLE);
					
				}
			}else{
				holder.more.setVisibility(View.GONE);
				holder.lay.setVisibility(View.VISIBLE);
			}
			
		}else if(groupPosition==2){
			if (data.get(keys.get(groupPosition)).size()< mAppData.attentionUserSize){
				if((childPosition == list.size())){
					holder.more.setVisibility(View.VISIBLE);
					holder.lay.setVisibility(View.GONE);
					holder.more.setText(R.string.loadmore);
				}else{
					holder.more.setVisibility(View.GONE);
					holder.lay.setVisibility(View.VISIBLE);
				}
			}else {
				holder.more.setVisibility(View.GONE);
				holder.lay.setVisibility(View.VISIBLE);
				
			}
		}
		
		if(list.size() <= childPosition)
			return convertView;
		String key = list.get(childPosition);
		Object obj = mAppData.cacheInformation.get(key);
		
		//适配好友
		if(obj instanceof CustomerInfoEntity){
			holder.sex.setVisibility(View.VISIBLE);
			if(getGroup(groupPosition).equals(friendRecent)){
				setMessage(holder,mAppData.messageCllection,key);
			}else{
				holder.msg.setVisibility(View.GONE);
			}
			CustomerInfoEntity cus = (CustomerInfoEntity)obj;
			holder.image.setOnClickListener(new onClick(convertView,false,false));
			if(cus.isShow() || cus.isAudit()){
				holder.v.setVisibility(View.VISIBLE);
			}else{
				holder.v.setVisibility(View.INVISIBLE);
			}
			String savepath = cus.getNormalHeadIcon();
			mImageLoader.displayImage(savepath, holder.image, cus.getSex(),false);
			mImageLoader.displayImageSexIcn(holder.sex, cus.getSex());
			holder.name_tv.setText(cus.getName()+"("+cus.getUsername()+")");
			holder.note_tv.setText(cus.getCusMessag());
		}
		
		//适配群
		if(obj instanceof GroupInfoEntity){
			setMessage(holder,mAppData.messageCllection,key);
			GroupInfoEntity group = (GroupInfoEntity) obj;
			holder.image.setOnClickListener(new onClick(convertView,true,group.getCreateCustomerID().equals(SmartFoxClient.getSmartFoxClient().getUserId())));
		
			holder.number.setText(group.getPersonNumber());
			holder.v.setImageBitmap(ic_cross);
			if(group.isSalon()){
				holder.v.setVisibility(View.VISIBLE);
			}else{
				holder.v.setVisibility(View.INVISIBLE);
			}
			String savepath = group.getNormalHeadIcon();
			mImageLoader.displayImage(savepath,holder.image,null,true);
			holder.name_tv.setText(group.getName());
			holder.note_tv.setText(group.getDescription());
		}
		return convertView;
	}

	private void setMessage(viewHolder holder,ConcurrentHashMap<String, List<MessageEntity>>  map,String key){
		if(map.containsKey(key)){
			holder.msg.setVisibility(View.VISIBLE);
			holder.msg.setText(String.valueOf(map.get(key).size()));
		}else
			holder.msg.setVisibility(View.GONE);
	}
	
	@Override
	public int getChildrenCount(int groupPosition) {
		//最返回最近20条联系人
		if (keys.get(groupPosition).equals(context.getString(R.string.recentGroup))) {
			if (data.get(keys.get(groupPosition)).size()>20) {
				return 20;
			}
		}
		if(keys.size() != 0&&data.get(keys.get(groupPosition)).size()!=0){
			//判断是否黑名单是否加载完
			if (keys.get(groupPosition).equals(blacklist)) {
				if (data.get(keys.get(groupPosition)).size()< mAppData.blackListSize) {
					ISBLACKLTMORE =true;
					return data.get(keys.get(groupPosition)).size()+1;
				}
			}
			//判断关注我的人是否加载完
			if (keys.get(groupPosition).equals(stranger)) {
				if (data.get(keys.get(groupPosition)).size()< mAppData.attentionUserSize) {
					ISSTRANGERMORE =true;
					return data.get(keys.get(groupPosition)).size()+1;
				}
			}
			return data.get(keys.get(groupPosition)).size();
			}
		else {
			ISBLACKLTMORE =false;
			ISSTRANGERMORE=false;
			return 0;
		}
	}

	@Override
	public long getCombinedChildId(long groupId, long childId) {
		return 0;
	}

	@Override
	public long getCombinedGroupId(long groupId) {
		return 0;
	}

	@Override
	public String getGroup(int groupPosition) {
		return keys.get(groupPosition);
	}
	/**
	 * 
	* @Title: isMORE 
	* @Description: 黑名单是否加载更多
	* @param @return    
	* @return boolean    
	* @throws
	 */
	public boolean isBlackltMore(){
		return ISBLACKLTMORE;
	}
	
	/**
	 * 
	* @Title: isStrangerMore 
	* @Description:关注我的人是否加载更多
	* @param @return    
	* @return boolean    
	* @throws
	 */
	public boolean isStrangerMore(){
		return ISSTRANGERMORE;
	}
	
	@Override
	public int getGroupCount() {
		return keys.size();
	}

	@Override
	public long getGroupId(int groupPosition) {
		return groupPosition;
	}

	@Override
	public View getGroupView(int groupPosition, boolean isExpanded,
			View convertView, ViewGroup parent) {
		    String key = keys.get(groupPosition);
		    if(key.equals(groupNew)){
		    	convertView = inflater.inflate(R.layout.group_item, null);
		    	ImageView head = (ImageView) convertView.findViewById(R.id.head_image);
		    	head.setImageResource(R.drawable.group_new);
		    	((TextView) convertView.findViewById(R.id.name)).setText(key);
				convertView.findViewById(R.id.note).setVisibility(View.GONE);
				convertView.findViewById(R.id.note_lay).setVisibility(View.GONE);
				convertView.findViewById(R.id.item_line).setVisibility(View.GONE);
				convertView.setBackgroundResource(R.drawable.listview_item_selector);
				convertView.setVisibility(View.GONE);
		    }else{
		    	 viewHolder  holder = null;
		        if(convertView != null)
		    	     holder = (viewHolder) convertView.getTag();
		    	if(holder == null){
		    		holder = new viewHolder();
		    		convertView = inflater.inflate(R.layout.knowledge_detail_expand_group, null);
		    		holder.groupView = (TextView)convertView.findViewById(R.id.expand_group_text);
		    		holder.number = (TextView)convertView.findViewById(R.id.group_number);
		    		holder.groupImage = (ImageView)convertView.findViewById(R.id.expand_group_head);
		    		convertView.setTag(holder);
		    	}
		       holder.groupView.setText(key);
		       holder.groupImage.setVisibility(View.VISIBLE);
		       //判断最近联系人最多显示20个
		       if (key.equals(context.getString(R.string.recentGroup))) {
		    	   if (data.get(key).size()>20) {
		    		   holder.number.setText("20");
				}else {
					 holder.number.setText(String.valueOf(data.get(key).size()));
				}
		       }else {
		    	   holder.number.setText(String.valueOf(data.get(key).size()));
			}
		       
		       
		       if(key.equals(stranger)){
		    	   int number = mAppData.attentionUserSize;
		    	   if(number == 0)
		    		   number = data.get(stranger).size();
		    	   holder.number.setText(String.valueOf(number));
		       }
		       	//获取黑名单的数据
		       if(key.equals(blacklist)){
		    	   int number = mAppData.blackListSize;
		    	   if(number == 0)
		    		   number = data.get(blacklist).size();
		    	   holder.number.setText(String.valueOf(number));
		       }
		       if(isExpanded)
		    	   holder.groupImage.setImageBitmap(bDown);
		       else
		    	   holder.groupImage.setImageBitmap(bUp);
		       convertView.setBackgroundDrawable(bg_draw);
		    }
		   return convertView;
	}

	@Override
	public boolean hasStableIds() {
		return false;
	}

	@Override
	public boolean isChildSelectable(int groupPosition, int childPosition) {
		return true;
	}

	@Override
	public boolean isEmpty() {
		return false;
	}

	@Override
	public void onGroupCollapsed(int groupPosition) {
           
	}

	@Override
	public void onGroupExpanded(int groupPosition) {
	}

	@Override
	public void registerDataSetObserver(DataSetObserver observer) {

	}

	@Override
	public void unregisterDataSetObserver(DataSetObserver observer) {

	}
	
	static  class viewHolder {
		ImageView v;
		LinearLayout line;
		TextView number;
		TextView msg; //未读消息
		ImageView image; // 头像
		ImageView sex; // 性别
		TextView name_tv; // 名称
		TextView note_tv; //简介
		TextView groupView;
		ImageView groupImage;
		public int groupId;
		public int childId;
		TextView more;
		LinearLayout lay;
	}
	
	private class onClick implements OnClickListener{
		boolean isGroup;
		View view;
		boolean isEditor;
		public onClick(View view,boolean isGroup,boolean isEditor){
			this.isGroup = isGroup;
			this.view = view;
			this.isEditor = isEditor;
		}
		
		@Override
		public void onClick(View v){
			viewHolder holder = (viewHolder)view.getTag();
			String id = FriendListExpandableAdapter.this.getChild(holder.groupId,holder.childId);
			String groupName = "";
			Class clazz;
			String key = "id";
			if(!isGroup){
				 groupName = FriendListExpandableAdapter.this.getGroup(holder.groupId);
				 clazz = FriendInformUI.class;
			}else if(isEditor){
				clazz = SalonNewActivity.class;
				key = "groupId";
			}else
				clazz = SalonInformationActivity.class;
			infoListener.intoInfo(clazz,id,groupName,key);
		}
	}
	
	public void add(Integer group, Integer child){
        if(map.containsKey(group)){		
        	map.get(group).add(child);
        }else{
        	ArrayList<Integer> arr = new ArrayList<Integer>();
        	arr.add(child);
        	map.put(group, arr);
        }
	}
	
	public void remove(Integer group, Integer child){
		if(map.containsKey(group))
		        map.get(group).remove(child);
	}
	/**
	 * 
	* @Title: setIntoInfoListener 
	* @Description: 设置监听器
	* @param @param infoListener    
	* @return void    
	* @throws
	 */
	public void setIntoInfoListener(IntoInfoListener infoListener){
		this.infoListener = infoListener;
	};

/**
 * 
* @ClassName: IntoInfoListener 
* @Description: 跳转信息的接口
* @author wangtao
* @date 2012-10-26 下午2:30:24
 */
  public interface IntoInfoListener{
	/**
	 * 
	* @Title: intoInfo 
	* @Description: 跳转信息界面的方法
	* @param @param cl
	* @param @param id
	* @param @param name
	* @param @param key    
	* @return void    
	* @throws
	 */
	void intoInfo(Class cl,String id ,String name,String key);
	
  }
}





